package org.xin.security.config.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.xin.common.util.XinUtil;
import org.xin.common.util.ip.IPUtil;
import org.xin.framework.config.exception.CloudException;
import org.xin.security.pojo.bo.SecurityUser;
import org.xin.security.common.SecurityUtil;
import org.xin.security.component.TokenComponent;
import org.xin.security.config.properties.SecurityConfigProperties;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：xin
 * @date ：Created in 2021/10/2
 * @desc <p> token过滤器 验证token有效性 </p>
 * @modified By：$
 * @version: $
 */
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenComponent tokenComponent;

    @Autowired
    private SecurityConfigProperties configProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        log.warn("访问IP：{}，URL : {}", IPUtil.getIpAddr(request), request.getRequestURL());
        try {
            SecurityUser securityUser = tokenComponent.getSecurityUser(request);
            if (XinUtil.noNull(securityUser) && XinUtil.isNull(SecurityUtil.getAuthentication())) {
                tokenComponent.verifyToken(securityUser);
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }catch (Exception e) {
            throw new CloudException(e);
        }

        chain.doFilter(request, response);
    }
}
